package com.chiancloud.shield.server.services.registry;

import com.chiancloud.shield.core.registry.info.ServiceInstanceData;
import com.chiancloud.shield.server.services.curator.CuratorServiceInstance;
import com.chiancloud.shield.server.services.curator.RegistryBinderService;
import com.google.common.base.Preconditions;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.x.discovery.ServiceDiscovery;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by wanghui on 14-8-20.
 */
public class ShieldRegistryService extends RegistryBinderService<ServiceInstanceData>
    implements RegistryViewForProviders{

    private ServiceInstanceData selfRegistration;

    public ShieldRegistryService(CuratorFramework curator,
                                 String basePath,
                                 ServiceDiscovery<ServiceInstanceData> discovery) {
        super(curator, basePath, discovery);
    }
    @Override
    public List<ServiceInstanceData> listInstancesByType(String serviceType) throws
            IOException {
        List<CuratorServiceInstance<ServiceInstanceData>> services =
                listInstances(serviceType);
        List<ServiceInstanceData> payloads = new ArrayList<>(services.size());
        for (CuratorServiceInstance<ServiceInstanceData> instance : services) {
            payloads.add(instance.payload);
        }
        return payloads;
    }

    @Override
    public ServiceInstanceData getSelfRegistration() {
        return selfRegistration;
    }

    private void setSelfRegistration(ServiceInstanceData selfRegistration) {
        this.selfRegistration = selfRegistration;
    }

    public void registerSelf(ServiceInstanceData instanceData, URL url) throws IOException {
        registerServiceInstance(instanceData, url);
        setSelfRegistration(instanceData);
    }

    @Override
    public void registerServiceInstance(
            ServiceInstanceData instanceData, URL url) throws IOException {
        Preconditions.checkNotNull(instanceData);
        Preconditions.checkNotNull(instanceData.id);
        Preconditions.checkNotNull(instanceData.serviceType);

        try {
            register(instanceData.serviceType, instanceData.id, url, instanceData);
        } catch (IOException e) {
            throw e;
        } catch (Exception e) {
            throw new IOException(e);
        }
    }
}
